// import apis from '@/api'
import { router } from '@/router'
import { message } from '@/utils/util.message'
import cookies from '@/utils/util.cookies'

const state = {
  token: undefined,
  userInfo: {}
}

const mutations = {
  login (state, { userInfo, token }) {
    state.userInfo = userInfo
    state.token = token
  },
  logout (state) {
    state.userInfo = {}
    state.token = undefined
  }
}

const actions = {
  async login ({ commit, dispatch }, { username, password }) {
    // const data = await apis.SYS_USER_LOGIN({ username, password })
    if (username === 'admin' && password === '123456') {
      const data = {
        userInfo: {
          username: 'admin',
          nickname: '管理员',
          roles: ['admin']
        },
        token: 'test123456'
      }
      // 将登录信息存入store
      commit('login', data)
      // 将登录信息存入本地db
      await dispatch('db/set', { dbName: 'sys', path: 'userInfo', value: data, user: true }, { root: true })
      // 将信息存入cookie
      cookies.set('token', data.token)
      cookies.set('userId', data.userInfo.username)
      await router.push('/')
    } else {
      message({
        type: 'error',
        message: '用户名或密码错误！'
      })
    }
  },
  async logout ({ commit }) {
    // await apis.SYS_USER_LOGOUT()
    commit('logout')
    await router.push({ name: 'login' })
  },
  async loadUserInfo ({ commit, dispatch }) {
    const userInfo = await dispatch('db/get', { dbname: 'sys', path: 'userInfo', user: true }, { root: true })
    console.log(userInfo)
    if (userInfo) {
      commit('login', userInfo)
    }
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
